package com.xhwl.centiotdata.ws;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;

/**
 * @description:
 * @author: wuyuhao
 * @createDate: 2022/10/18 15:01
 */
@Slf4j
public class MyWebSocketClient extends WebSocketClient {

    public MyWebSocketClient(URI uri) {
        super(uri);
    }

    private final Object lock = new Object();

    private Object result = null;

    private CountDownLatch downLatch = null;

    public Object sendData(Object object) {
        synchronized (lock) {
            downLatch = new CountDownLatch(1);
            sendImpl(object);
            try {
                downLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return result;
        }
    }

    public void sendImpl( Object object ){
        if(object instanceof String){
            super.send((String)object);
        }else if(object instanceof byte[]){
            super.send((byte[])object);
        }
    }

    @Override
    public void onOpen(ServerHandshake handshake) {
        log.info("onOpen...");
    }

    @Override
    public void onMessage(String message) {
        log.info("onMessage String...");
        result = message;
        if (downLatch != null) {
            downLatch.countDown();
        }
    }

    public void onMessage(ByteBuffer bytes) {
        log.info("onMessage ByteBuffer...");
        result = bytes;
        if (downLatch != null) {
            downLatch.countDown();
        }
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        log.info("onClose...");
    }

    @Override
    public void onError(Exception e) {
        log.error("onError: {}", e.getMessage());
    }
}
